# 2023年秋季学期《高等程序设计语言》期末考核项目:学生信息管理系统

import re
import os
import os.path
 
os.chdir(os.path.dirname(os.path.abspath(__file__)))

if not os.path.exists('newdir'):
    os.mkdir('newdir')
def menm():
        #展示界面
        print('\n\n','学生信息管理系统'.center(60,'='),'\n\n')
        print('目录'.center(60),'\n')
        print('\t\t\t\t\t\t1、录入学生信息')
        print('\t\t\t\t\t\t2、查找学生信息')
        print('\t\t\t\t\t\t3、删除学生信息')
        print('\t\t\t\t\t\t4、修改学生信息')
        print('\t\t\t\t\t\t5、排序')
        print('\t\t\t\t\t\t6、统计学生总人数')
        print('\t\t\t\t\t\t7、显示所有学生信息')
        print('\t\t\t\t\t\t8、打开学生信息文件')
        print('\t\t\t\t\t\t9、退出系统','\n\n')
        print('-----------------------------------------------------------','\n\n')


def main():
    if not os.path.exists('stuinfomgr.txt'):
        with open('stuinfomgr.txt','wt',encoding="UTF-8") as fp:
               fp.write('学号\t\t姓名\t\t性别\t\t数学\t\t物理\t\tpython\t\t平均成绩\n')
        #功能块
    while True:
        menm()
        select = int(input('\n请选择功能:'))

        if select == 1:
            while True:
                stu_id=input('\n请输入学生学号:')
                stu_name=input('\n请输入学生姓名:')
                stu_gender=input('\n请输入学生性别:')
                stu_score_math = int(input('\n请输入数学成绩:'))
                stu_score_phy = int(input('\n请输入物理成绩:'))
                stu_score_pyth = int(input('\n请输入python成绩:'))
                stu_ave=(stu_score_math+stu_score_phy+stu_score_pyth)/3
                 
                with open('stuinfomgr.txt','a+') as fp:
                 fp.writelines(['\n',stu_id,'\t\t',stu_name,'\t\t',stu_gender,'\t\t',str(stu_score_math),'\t\t',str(stu_score_phy),'\t\t',str(stu_score_pyth),'\t\t',str( stu_ave)])
                selec= input('\n是否继续输入学生信息? y/n: ')
                if selec != "y":
                    break
                    
                       

        elif select == 2:
            while True:
                # 读取学生信息文件stuinfomgr.txt中的信息，并按“学号”或“姓名”查找指定学生
                # 将查找到的学生的所有信息“学号、姓名、性别、数学成绩、物理成绩、Python成绩、平均成绩”用print输出
                # 如果输入的“学号”或“姓名”不存在，用print反馈“未查到该学生信息”
                char = input("\n请输入待查询的学生的学号或姓名:")
                with open("stuinfomgr.txt", "r", encoding="UTF-8") as fp:
                    lst = fp.readlines()

                for item in lst:
                    if char in item[:9]:
                        lst_info = item.split(sep="\t\t")
                        print(
                            "\n姓名:",
                            lst_info[1],
                            "\t学号:",
                            lst_info[0],
                            "\t性别:",
                            lst_info[2],
                        )
                        print("数学成绩：", lst_info[3], end="\t")
                        print("物理成绩：", lst_info[4], end="\t")
                        print("Python成绩:", lst_info[5])
                        print("平均成绩：", lst_info[6], "\n")
                        break
                else:
                    print("未查到学生信息")
                # 询问是否继续查找学生信息
                selec = input("是否继续查找学生信息? y/n:")
                if selec != "y":
                    break
        elif select ==3:
                while True:
                 char =input('\n请输入待删除的学生信息或姓名:')
                 with open ('stuinfomgr.txt','r',ending='UTF_8')as fp:
                    lst=fp.readlines()

                 k=0
                 for item in lst[2:]:
                         if char in item:
                            break 
                         k+=1
                 else:
                         print('未查到学生信息')
                         break
                         
                 
                del lst[k + 2]

                with open("stuinfomgr.txt", "w", encoding="UTF-8") as fp:
                    fp.writelines(lst)

                selec =input('是否继续删除学生信息?y/n:')
                if selec !='y':
                         break
                         
        elif select ==4:
            while True:
                with open('stuinfomgr.txt','r',encoding='UTF-8') as fp:
                    lst =fp.readlines()


                lst_of_dic =[]
                if len (lst)>=2:
                   for item in lst[2:]:         
                       elem =item.split(sep='\t\t')
                       dic ={'学号':elem[0],'姓名':elem[1],'性别':elem[2],'数学':elem[3],'物理':elem[4],'python':elem[5],}
                       lst_of_dic.append(dic)
                else:
                    print('无学生信息，请先录入\n\n')
                    break
                             

                k = 0
                char =input('\n请输入待修改的学生学号或姓名:')
                for item in lst_of_dic:
                    if char == item['姓名']or char == item['学号']:
                        break 
                    k +=1
                else:
                    print('未查到学生信息')
                    break
                         
                            
                while True:
                   scro =input ('请输入待修改的项(学号/姓名/性别/数学/物理/python):')
                   if scro in '请输入待修改的项(学号/姓名/性别/数学/物理/python)':
                            va1 = input ('\n请输入修改后的内容:')
                            lst_of_dic[k][scro] = va1
                   else:
                        print('关键字不存在')
                        break
                                

                   sel = input('\n是否继续修改该学生信息? :y/n:')
                   if sel !='y':
                               break
                            
                         
                stu_ave = (
                    int(lst_of_dic[k]["数学"])
                    + int(lst_of_dic[k]["物理"])
                    + int(lst_of_dic[k]["Python"])
                ) / 3
                lst_ch = "".join(
                    [
                        lst_of_dic[k]["学号"],
                        "\t\t",
                        lst_of_dic[k]["姓名"],
                        "\t\t",
                        lst_of_dic[k]["性别"],
                        "\t\t",
                        str(lst_of_dic[k]["数学"]),
                        "\t\t",
                        str(lst_of_dic[k]["物理"]),
                        "\t\t",
                        str(lst_of_dic[k]["Python"]),
                        "\t\t",
                        str(stu_ave),
                        "\n",
                    ]
                )

                lst[k + 2] = lst_ch

                # 将修改后的内容写进新文件
                with open("stuinfomgr.txt", "w", encoding="UTF-8") as fp:
                    fp.writelines(lst)
                # 询问是否继续修改其他学生信息
                selec = input("是否继续修改下一个学生的信息? y/n:")
                if selec != "y":
                    break

        elif select == 5:
            with open('stuinfomgr.txt',encoding='UTF-8') as fp:
                lst = fp.readlines()
                    
            lst_of_dic = []
            if len(lst) >= 2:
                for item in lst[2:]:
                    elem = item.split(sep='\t\t')
                    av = elem[6].split(sep='\n')[0]
                    dic = {'学号':elem[0],'姓名':elem[1],'性别':elem[2],'数学':elem[3],'物理':elem[4],'Python':elem[5],'平均分':str[av]}
                    lst_of_dic.append(dic)

            else:
                print('无学生信息,请先录入\n\n')
                break
                    
            choice = input('请输入排序数目（学号/数学/物理/Python/平均分）: ')
            if choice in '学号/数学/物理/Python/平均分':
                sen_or_desen = input('请输入按升序排序还是降序排序(升降):')
                if sen_or_desen == '升':
                    for item1 in range(len(lst_of_dic)-1):
                        for item2 in range(item1,len(lst_of_dic)):
                            if int(lst_of_dic[item1][choice]) >= int(lst_of_dic[item2][choice]):
                                lst_of_dic[item1],lst_of_dic[item2]=lst_of_dic[item2],lst_of_dic[item1]
                elif sen_or_desen == '降':
                     for item1 in range(len(lst_of_dic)-1):
                        for item2 in range(item1,len(lst_of_dic)):
                            if int(lst_of_dic[item1][choice]) <= int(lst_of_dic[item2][choice]):
                                 lst_of_dic[item1],lst_of_dic[item2] = lst_of_dic[item2],lst_of_dic[item1]
                else:
                            print('关键字不存在')
            lst = []
            N = len(lst_of_dic)
            for item in range(N):
                stg = "".join(
                    [
                        "\n",
                        lst_of_dic[item]["学号"],
                        "\t\t",
                        lst_of_dic[item]["姓名"],
                        "\t\t",
                        lst_of_dic[item]["性别"],
                        "\t\t",
                        lst_of_dic[item]["数学"],
                        "\t\t",
                        lst_of_dic[item]["物理"],
                        "\t\t",
                        lst_of_dic[item]["Python"],
                        "\t\t",
                        lst_of_dic[item]["平均成绩"],
                    ]
                )
                lst.append(stg)

            format_title = "{0:^6}\t{1:^6}\t{2:^6}\t{3:^6}\t{4:^6}\t{5:^1}\t{6}"
            print("排序后的结果: ")
            print(format_title.format("学号", "姓名", "性别", "数学", "物理", "Python", "平均分"))
            for item in lst_of_dic:
                print(
                    format_title.format(
                        item.get("学号"),
                        item.get("姓名"),
                        item.get("性别"),
                        item.get("数学"),
                        item.get("物理"),
                        item.get("Python"),
                        item.get("平均成绩"),
                    )
                )

            with open("stuinfomgr.txt", "w+", encoding="UTF-8") as fp:
                fp.write(
                    "学号\t\t姓名\t\t性别\t\t数学\t\t物理\t\tPython\t\t平均成绩\n------------------------------------------------------------------------------------"
                )

            # 将修改后的内容写入新文件
            with open("stuinfomgr.txt", "a+", encoding="UTF-8") as fp:
                fp.writelines(lst)
                      


        elif select == 6:
      
            with open('stuinfomgr.txt','r',encoding="UTF-8") as fp:
                    lst = fp.readlines()

            print('\n共有学生',len(lst)-2,'人\n')

        elif select == 7:
            try:
                       with open('stuinfomgr.txt','r',encoding="UTF-8") as fp:
                            lst = fp.readlines()

                       lst_of_dic = []
                       if len(lst) >= 2:
                            for item in lst[2:]:
                                elem = item.split(sep='\t\t')
                                dic = {'学号':elem[0],'姓名':elem[1],'性别':elem[2],'数学':elem[3],'物理':elem[4],'Python':elem[5],'平均分':elem[6]}
                                lst_of_dic.append(dic)
                       else:
                            print('无学生信息，请先录入\n\n')
                             
                            format_title='{0:^6}\t{1:^6}\t{2:^6}\t{3:^6}\t{4:^6}\t{5:^1}\t{6}'
                            format_title1='{0:^9}\t{1:^6}\t{2:^7}\t{3:^8}\t{4:^8}\t{5:^8}\t{6:.2f}'
                            print(format_title.format('学号','姓名','性别','数学','物理','Python','平均分'))

                       for item in lst_of_dic:

                            stu_ave = (int(item['数学'])+int(item['物理'])+int(item['Python']))/3
                            print(format_title1.format(item.get('学号'),
                                                       item.get('姓名'),
                                                       item.get('性别'),
                                                       item.get('数学'),
                                                       item.get('物理'),
                                                       item.get('Python'),
                                                       stu_ave))
            except:
                        print('学生信息文件不存在')

        elif select == 8:
                    path = os.getcwd()
                    filename = 'stuinfomgr.txt'
                    try:
                        os.startfile(os.path.join(path,filename))
                    except:
                        print('学生信息文件不存在')
        # 功能模块9：退出小程序，并删除本程序创建的所有文件（stuinfomgr.txt）和目录（newdir）
        elif select == 9:
            print("\n\n程序已终止\n\n")
            file_path = os.path.join("newdir", "stuinfomgr.txt")

            try:
                # 删除stuinfomgr.txt文件
                os.remove(file_path)
                print(f"文件 {file_path} 已删除")
            except FileNotFoundError:
                print(f"文件 {file_path} 不存在")

            try:
                # 删除newdir目录
                os.rmdir("newdir")
                print("目录 newdir 已删除")
            except FileNotFoundError:
                print("目录 newdir 不存在")

            break
        else:
            print("\n功能不存在,请重新输入\n")


if __name__ == "__main__":
    main()

                                                        

               
